<!--
 * @Author: Lin Ming
 * @Date: 2021-02-24 23:46:30
 * @LastEditors: Lin Ming
 * @LastEditTime: 2021-02-25 17:42:04
 * @FilePath: \vue-zheye\src\components\ValidateInput.vue
-->
<template>
  <div class="lm-validate-input validate-input-container pb-3">
    <label for="lm-input">{{title}}</label>
    <input id="lm-input" type="text" class="form-control" :class="{'is-invalid':inputRef.error}" @input="updateValue" :value="inputRef.val" @blur="validateInput" v-bind="$attrs">
    <span v-if="inputRef.error">{{inputRef.message}}</span>
  </div>
</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, onMounted } from 'vue'
import { emitter } from './ValidateForm.vue'
const emailReg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
interface RuleProp {
  type: 'required' | 'email' ;
  message: string;
}
export type RulesProp = RuleProp[]
export default defineComponent({
  name: 'ValidateInput',
  props: {
    rules: Array as PropType<RulesProp>,
    modelValue: String,
    title: String
  },
  inheritAttrs: false,
  setup (props, context) {
    const inputRef = reactive({
      val: props.modelValue || '',
      error: false,
      message: ''
    })
    const updateValue = (e: KeyboardEvent) => {
      const targetValue = (e.target as HTMLInputElement).value
      console.log('targetValue', targetValue)
      inputRef.val = targetValue
      context.emit('update:modelValue', targetValue)
    }
    const validateInput = () => {
      if (props.rules) {
        const allPassed = props.rules.every(rule => {
          let passed = true
          inputRef.message = rule.message
          switch (rule.type) {
            case 'required':
              passed = (inputRef.val.trim() !== '')
              break
            case 'email':
              passed = emailReg.test(inputRef.val)
              break
          }
          return passed
        })
        inputRef.error = !allPassed
        return allPassed
      }
      return true
    }
    // 将事件发射出去，其实就是把验证函数发射出去
    onMounted(() => {
      emitter.emit('form-item-created', validateInput)
    })
    return {
      inputRef,
      validateInput,
      updateValue
    }
  }
})
</script>
